package com.spring.demo.publicutil.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {
    public static void main(String[] args) {
        // 初始化线程池
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                1, // 核心线程数
                5, // 最大线程数
                10, // 线程空闲时间
                TimeUnit.SECONDS, // 时间单位
                new ArrayBlockingQueue<>(10) // 任务队列
        );

        // 提交10个任务给线程池
        for (int i = 0; i < 10; i++) {
            int taskNumber = i + 1;
            executorService.submit(() -> {
                System.out.println("任务 " + taskNumber + " 正在执行，线程: " + Thread.currentThread().getName());
                try {
                    // 模拟任务执行时间
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务 " + taskNumber + " 执行完成");
            });
        }
        // 关闭线程池
        executorService.shutdown();
        try {
            // 等待所有任务完成
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }

        System.out.println("所有任务已完成");
    }
}
